<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>023-面向对象-拖拽.html</title>
</head>
<body>
	
</body>
<script>
	function Drag(options){
		//1.罗列
		this.oBox = null;
		this.width = options.width;
		this.height = options.height;
		this.background = options.background;
		this.disX = 0;
		this.disY = 0;
		//2.初始化
		this.init();
		//3.绑定事件
		this.bindEvent();
	}
	Drag.prototype.init = function(){
		this.oBox = document.createElement('div');
		this.oBox.style.position = 'absolute';
		this.oBox.style.left = 0;
		this.oBox.style.top = 0;
		this.oBox.style.width = this.width + 'px';
		this.oBox.style.height = this.height + 'px';
		this.oBox.style.background = this.background;
		document.body.appendChild(this.oBox);
	}
	Drag.prototype.bindEvent = function(){
		this.oBox.onmousedown = function(ev){
			var oEvent = ev || event;
			this.disX = oEvent.clientX - this.oBox.offsetLeft;
			this.disY = oEvent.clientY - this.oBox.offsetTop;
			/*
			document.onmousemove = function(ev){
				var oEvent = ev || event;
				this.oBox.style.left = oEvent.clientX -this.disX + 'px';
				this.oBox.style.top = oEvent.clientY - this.disY + 'px';
			}.bind(this);
			document.onmouseup = function(){
				document.onmousemove = null;
				document.onmouseup = null;
			}
			*/
			document.onmousemove = this.fnMove.bind(this);
			document.onmouseup = this.fnUp;
		}.bind(this);
	}
	Drag.prototype.fnMove = function(ev){
		var oEvent = ev || event;
		console.log(this);
		this.oBox.style.left = oEvent.clientX - this.disX + 'px';
		this.oBox.style.top = oEvent.clientY - this.disY + 'px';
	}
	Drag.prototype.fnUp = function(){
		document.onmousemove = null;
		document.onmouseup = null;
	}
	function LimitDrag(options){
		Drag.call(this,options);
	}
	LimitDrag.prototype = Object.create(Drag.prototype);
	LimitDrag.prototype.constructor = LimitDrag;
	LimitDrag.prototype.fnMove = function(ev){
		var oEvent = ev || event;
		var l = oEvent.clientX - this.disX;
		var t = oEvent.clientY - this.disY;
		if(l<0){
			l = 0;
		}else if(l > window.innerWidth - this.oBox.offsetWidth){
			l = window.innerWidth - this.oBox.offsetWidth;
		}
		if(t<0){
			t = 0;
		}else if(t > window.innerHeight - this.oBox.offsetHeight){
			t = window.innerHeight - this.oBox.offsetHeight;
		}
			this.oBox.style.left = l + 'px';
			this.oBox.style.top =  t + 'px';
	}
	new Drag({
		width:100,
		height:100,
		background:'skyblue'
	})
	new Drag({
		width:200,
		height:200,
		background:'green'
	})
	new LimitDrag({
		width:300,
		height:300,
		background:'gray'
	})
</script>
</html>